package ar.edu.itba.bundundu;

import java.io.IOException;
import java.net.URL;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.itba.bundundu.dao.UserDao;
import ar.edu.itba.bundundu.domain.UserIds;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.Link;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclNamespace;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;


@SuppressWarnings("serial")
public class RetrieveTokenServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

  }

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
	    RequestDispatcher dispatcher;
	    dispatcher = getServletContext().getRequestDispatcher("/retrievetoken.jsp");
	    try {
	      CalendarService calendar = new CalendarService("exampleCo-exampleApp-1");
	      String onetimeUseToken = AuthSubUtil.getTokenFromReply(req
	          .getQueryString());
	      String sessionToken = AuthSubUtil.exchangeForSessionToken(
	          onetimeUseToken, null);
	      calendar.setAuthSubToken(sessionToken, null);
	      req.setAttribute("onetime", onetimeUseToken);
	      req.setAttribute("sessionToken", sessionToken);

	      // Almacenar el session token
	      Long uid= Long.valueOf(req.getParameter("fb_sig_user"));
	      UserIds user = new UserIds(uid, sessionToken);
	      req.setAttribute("fb_usr", user);
	      
	      //Obtener el email
	      CalendarFeed calendarFeed =
	        calendar.getFeed(new URL("http://www.google.com/calendar/feeds/default/owncalendars/full"),
	            CalendarFeed.class);
	      CalendarEntry calEntry = calendarFeed.getEntries().get(0);
	      Link link = calEntry.getLink(AclNamespace.LINK_REL_ACCESS_CONTROL_LIST,
	          Link.Type.ATOM);
	      AclFeed aclFeed = calendar.getFeed(new URL(link.getHref()), AclFeed.class);
	      AclEntry aclEntry = aclFeed.getEntries().get(0);
	      String email = aclEntry.getScope().getValue();        
	      user.setEmail(email);
	      // hacer permanente
	      UserDao.save(user);
	      
	    } catch (Exception e) {
	      // TODO Auto-generated catch block
	      
	    }
	    
	    dispatcher.forward(req, resp);
	}
}
